package services;

import com.example.maze.ConnectionInfo;

import tw.edu.tku.im.maze.DeliveryListenerI;
import tw.edu.tku.im.maze.RepPacket;
import tw.edu.tku.im.maze.RoomListDeliverer;
import tw.edu.tku.im.maze.RoomListReq;
import tw.edu.tku.im.maze.TimeOutRep;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

public class UpdateRoomsListService extends IntentService
                                    implements DeliveryListenerI{
  
   //[ -------------------- constant --------------------
   public  static final String BROADCAST_ACTION= "updateRoomsList";   
   private static final int    DELAY_TIME      = 8000;    // milli second
   //] -------------------- constant --------------------
   
   //[ -------------------- construct --------------------
   public UpdateRoomsListService()            { super("UpdateRoomsList"); }
   public UpdateRoomsListService(String name) { super(name); }
   //[ -------------------- construct --------------------
   
   // --------------------------------------------------
   @Override
   protected void onHandleIntent(Intent intent) {
      //[ 斷線時 theUpdateService= null, 使重啟得以判定是否造新 Service
      ConnectionInfo.theUpdateService= this;
      
      RoomListDeliverer mRoomListDeliverer= new RoomListDeliverer();
      try{
         while(ConnectionInfo.roomListupdateLoop == ConnectionInfo.CONTINUE) {
//android.util.Log.d("DebugMsg","updateing");
            mRoomListDeliverer.deliver(new RoomListReq(), this);
            Thread.sleep(DELAY_TIME);
            if(ConnectionInfo.roomListupdateLoop == ConnectionInfo.INTERRUPT) {
               ConnectionInfo.theUpdateService= null;
//android.util.Log.d("DebugMsg","INTERRUPT"); 
            }
         }
      } catch(Exception e) {}
   }
   // --------------------------------------------------
   @Override
   public void processReply(RepPacket rep) {
//android.util.Log.d("DebugMsg","reply"); 
      if(rep instanceof TimeOutRep) {
         return; //: 直接重連即可
      } else {
         Intent localIntent= new Intent(BROADCAST_ACTION);
         localIntent.putExtra("packet", rep);
         LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
      }
   }
   // --------------------------------------------------
}
